import type {
  Settings as LayoutSettings,
  BasicLayoutProps,
  MenuDataItem,
} from '@ant-design/pro-layout';
import { PageLoading, ProBreadcrumb } from '@ant-design/pro-layout';
import { history } from 'umi';
import {
  HomeOutlined,
  AppstoreOutlined,
  DashboardOutlined,
  ClockCircleOutlined,
  CompassOutlined,
  CoffeeOutlined,
  RadarChartOutlined,
  FundOutlined,
  TagsOutlined,
  SmileOutlined,
  BarChartOutlined,
  MenuUnfoldOutlined,
  MailOutlined,
  CrownOutlined,
} from '@ant-design/icons';
import { message } from 'antd';
import { getMenu } from './api/menu';
import './global.less';
import './api/axiosUtils.js';
import Header from './components/Header';
const loginPath = '/login';
const appltPath = '/applt';

const iconEnum: any = {
  home: <HomeOutlined />,
  'appstore-o': <AppstoreOutlined />,
  dashboard: <DashboardOutlined />,
  'clock-circle-o': <ClockCircleOutlined />,
  compass: <CompassOutlined />,
  coffee: <CoffeeOutlined />,
  'radar-chart': <RadarChartOutlined />,
  fund: <FundOutlined />,
  tags: <TagsOutlined />,
  smile: <SmileOutlined />,
  'bar-chart': <BarChartOutlined />,
  'menu-fold': <MenuUnfoldOutlined />,
  mail: <MailOutlined />,
  crown: <CrownOutlined />,
  none: <AppstoreOutlined />,
};

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  // 动态菜单
  menu: any;
  settings?: any;
  currentUser?: any;
}> {
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath || appltPath) {
    if (!localStorage.token) {
      history.push(loginPath);
    }

    let settings: any = JSON.parse(localStorage.config);
    let userInfo = JSON.parse(localStorage.userInfo);
    // console.log(settings);

    let menuData: any = await getMenu(userInfo.username);
    menuData = menuData.data[0].children; // ;

    // console.log(menuData);

    // 模拟后台取得的api 数据
    // menuData = [
    //   {
    //     name: 'Home',
    //     icon: 'HeartOutlined',
    //     path: '/home',
    //     component: '@/pages/index',
    //   },
    //   {
    //     name: '系统管理',
    //     // icon: 'SmileOutlined',
    //     path: '/system/user',
    //     meta: {
    //       closeable: true,
    //       isShow: true,
    //     },
    //   },
    // ];
    return {
      menu: menuData,
      settings,
      currentUser: userInfo,
    };
  }
  return {
    menu: [],
    settings: {},
  };
}

//  递归生成菜单
const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] =>
  menus.map(({ icon, children, meta, ...item }) => {
    console.log(meta);

    const obj = {
      ...item,
      //  icon: icon && IconMap[icon as string],
      // 方案一： 此用法会把所有的图标库引入，造成增加工程3M大小，请谨用
      // icon: icon && React.createElement(Icon[icon]),
      // 方案二： 建议用此方案，只引入用到的图标，避免图标库全部引入
      icon: icon && iconEnum[icon as string],
      children: children && loopMenuItem(children),
    };

    if (meta && !meta.isShow && meta.isShow != undefined) obj.hideInMenu = true;

    // console.log(item.name, icon);
    return obj;
  });

export const layout = ({
  initialState,
}: {
  initialState: {
    menu: MenuDataItem[];
    settings: any;
  };
}): BasicLayoutProps => {
  // 随机布局模式 写着玩下面的layout注释就可以解除
  // let layout: any = ['mix', 'side', 'top'][Math.ceil(Math.random() * 3) - 1];
  // console.log(layout);
  if (!initialState) return {};

  return {
    //  动态菜单支持
    // menuDataRender: () => loopMenuItem(initialState.menu),
    // 是否去除页面的margin
    disableContentMargin: false,
    headerContentRender: () => {
      return <ProBreadcrumb />;
    },
    rightContentRender: () => <Header></Header>,
    // layout,
    //  修补：二级图标正常显示2021.7.8，动态菜单下不管用，只会显示图标的名称
    /*
     menuItemRender: (menuItemProps, defaultDom) => {
      if (
        menuItemProps.isUrl || !menuItemProps.path) {
        return defaultDom;
      }
      // 支持二级菜单显示icon
      return (
       <Link to={menuItemProps.path}>
          {menuItemProps.pro_layout_parentKeys 
          && menuItemProps.pro_layout_parentKeys.length > 0 &&
          menuItemProps.icon}{defaultDom}
        </Link>
    );
  },
  */

    onPageChange: () => {
      if (history.location.pathname !== loginPath && !localStorage.token) {
        message.error('抱歉您还没有登录');
        history.push(loginPath);
      }
    },
    // navTheme: theme,
    ...initialState?.settings,
  };
};
